package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dao.CategoryDao;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetdmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {
    @Autowired
    CategoryDao categoryDao;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetdmealService setdmealService;

    @Override
    public IPage<Category> querypage(Map map) {
        //先写条件构造器LambdaQueryWrapper             //记得new
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        //调用like模糊查询
        queryWrapper.like(map.get("name") != null && !"".equals(map.get("name")), Category::getName, map.get("name"));

        //将所有的数据封装成一个page
        IPage<Category> page = new Page<Category>(Long.parseLong((String) map.get("page")), Long.parseLong((String) map.get("pageSize")));

        categoryDao.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public void remove(Long id) {


        //添加查询条件，根据分类id进行查询菜品数据
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);

        int count = dishService.count(dishLambdaQueryWrapper);
        //如果分类和菜品已经关联，就抛出异常提醒不能删除
        if (count > 0){
            throw new  CustomException("当前分类已与菜品已经关联不可以删除");
        }
        //添加查询条件
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper= new LambdaQueryWrapper<>();

        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);

        int count1 = setdmealService.count(setmealLambdaQueryWrapper);

        if (count1 > 0){
            throw new CustomException("当前分类下已与套餐关联，无法删除");
        }
        super.removeById(id);
    }
}
